import React, { useState, useCallback, useEffect } from 'react'
import { Card, Row, Col, Space } from 'antd'
import ExperimentParameters from './ExperimentParameters'
import ExperimentControl from './ExperimentControl'
import MotionControl from './MotionControl'
import SyncStatus from './SyncStatus'
import { useWebSocket } from '../../hooks/useWebSocket'
import './ControlPanel.css'

const ControlPanel = () => {
  const { pendulumState, sendKey, connected } = useWebSocket()
  
  // 实验参数状态
  const [parameters, setParameters] = useState({
    length: 120.0,
    angle: 5.0,
    smoothing: 0.8,
    prediction: 0.12
  })
  
  // 实验状态
  const [experimentState, setExperimentState] = useState({
    running: false,
    time: 0.00,
    periodCount: 0
  })
  
  // 运动控制状态
  const [motionInputs, setMotionInputs] = useState({
    nValue: '',
    mValue: ''
  })

  // 更新参数
  const updateParameter = useCallback((key, value) => {
    setParameters(prev => ({
      ...prev,
      [key]: value
    }))
    
    // 发送到后端
    if (connected && sendKey) {
      switch (key) {
        case 'length':
          sendKey('2', { m: value })
          break
        case 'angle':
          sendKey('a', { angle: value })
          break
        case 'smoothing':
          // 发送平滑参数
          sendKey('smoothing', { value })
          break
        case 'prediction':
          // 发送预测参数
          sendKey('prediction', { value })
          break
        default:
          break
      }
    }
  }, [connected, sendKey])

  // 实验控制操作
  const handleExperimentControl = useCallback((action) => {
    if (!connected || !sendKey) return
    
    switch (action) {
      case 'start':
        setExperimentState(prev => ({
          ...prev,
          running: !prev.running
        }))
        sendKey('d0')
        break
      case 'reset':
        setExperimentState({
          running: false,
          time: 0.00,
          periodCount: 0
        })
        sendKey('reset')
        break
      case 'd0':
        sendKey('d0')
        break
      case 'd1':
        sendKey('d1')
        break
      case 'getPendulumLength':
        // 获取摆长数据
        fetch('http://127.0.0.1:5000/get_pendulum_length')
          .then(r => r.json())
          .then(data => {
            if (data.success && data.length !== undefined) {
              setParameters(prev => ({
                ...prev,
                length: data.length
              }))
            }
          })
          .catch(error => {
            console.error('获取摆长数据失败:', error)
          })
        break
      case 'getPendulumAngle':
        // 获取角度数据
        fetch('http://127.0.0.1:5000/get_pendulum_angle')
          .then(r => r.json())
          .then(data => {
            if (data.success && data.angle !== undefined) {
              setParameters(prev => ({
                ...prev,
                angle: data.angle
              }))
            }
          })
          .catch(error => {
            console.error('获取角度数据失败:', error)
          })
        break
      default:
        break
    }
  }, [connected, sendKey])

  // 运动控制操作
  const handleMotionControl = useCallback((action, value = null) => {
    if (!connected || !sendKey) return
    
    switch (action) {
      case 'upM':
        sendKey('w')
        break
      case 'downM':
        sendKey('s')
        break
      case 'upU':
        sendKey('3')
        break
      case 'downU':
        sendKey('4')
        break
      case 'upN':
        sendKey('6')
        break
      case 'downN':
        sendKey('7')
        break
      case 'clear':
        setMotionInputs({
          nValue: '',
          mValue: ''
        })
        break
      case 'sendN':
        if (motionInputs.nValue) {
          sendKey('n', { value: parseInt(motionInputs.nValue) })
        }
        break
      case 'sendM':
        if (motionInputs.mValue) {
          sendKey('m', { value: parseInt(motionInputs.mValue) })
        }
        break
      default:
        break
    }
  }, [connected, sendKey, motionInputs])

  // 更新运动控制输入
  const updateMotionInput = useCallback((key, value) => {
    setMotionInputs(prev => ({
      ...prev,
      [key]: value
    }))
  }, [])

  // 处理WebSocket数据更新
  useEffect(() => {
    if (pendulumState) {
      // 更新实验状态
      if (pendulumState.time !== undefined) {
        setExperimentState(prev => ({
          ...prev,
          time: pendulumState.time
        }))
      }
      
      if (pendulumState.periodCount !== undefined) {
        setExperimentState(prev => ({
          ...prev,
          periodCount: pendulumState.periodCount
        }))
      }
      
      if (pendulumState.running !== undefined) {
        setExperimentState(prev => ({
          ...prev,
          running: pendulumState.running
        }))
      }
      
      // 更新参数
      if (pendulumState.length !== undefined) {
        setParameters(prev => ({
          ...prev,
          length: pendulumState.length
        }))
      }
      
      if (pendulumState.angle !== undefined) {
        setParameters(prev => ({
          ...prev,
          angle: pendulumState.angle
        }))
      }
    }
  }, [pendulumState])

  return (
    <div className="control-panel">
      <Row gutter={[0, 16]}>
        {/* 实验参数设置 */}
        <Col span={24}>
          <Card title="实验参数设置" size="small">
            <ExperimentParameters 
              parameters={parameters}
              onParameterChange={updateParameter}
            />
          </Card>
        </Col>
        
        {/* 实验控制 */}
        <Col span={24}>
          <Card title="实验控制" size="small">
            <ExperimentControl 
              experimentState={experimentState}
              onControl={handleExperimentControl}
              connected={connected}
            />
          </Card>
        </Col>
        
        {/* 运动控制 */}
        <Col span={24}>
          <Card title="运动控制" size="small">
            <MotionControl 
              motionInputs={motionInputs}
              onControl={handleMotionControl}
              onInputChange={updateMotionInput}
              connected={connected}
            />
          </Card>
        </Col>
        
        {/* 同步状态 */}
        <Col span={24}>
          <Card title="同步状态" size="small">
            <SyncStatus />
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default ControlPanel
